package com.yizisu.basemvvm.utils

import android.content.Context
import android.net.*
import com.yizisu.basemvvm.app

/**
 * 若红楼梦空，亦初心不变
 * 作者：thinker
 * 包名：com.yizisu.basemvvm.utils
 * 时间：2019/5/17 8:59
 * 描述：
 */
object NetWorkUtils {
    private val netServer by lazy {
        app.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    }
    /**
     * 网络是否链接
     */
    private var netWorkConnect = true
    val isNetWorkConnect: Boolean
        get() {
            return netWorkConnect
        }
    /***
     * 当前链接是否wifi
     * null:没有网络链接
     * true:wifi
     * false:有链接但不是wifi
     */
    val isWifi: Boolean?
        get() {
            if (!isNetWorkConnect) {
                return null
            }
            val info = netServer.activeNetworkInfo
            return info != null && info.isAvailable && info.type == ConnectivityManager.TYPE_WIFI
        }
    private val callBack = object : ConnectivityManager.NetworkCallback() {
        override fun onCapabilitiesChanged(network: Network, networkCapabilities: NetworkCapabilities) {
            super.onCapabilitiesChanged(network, networkCapabilities)
        }

        override fun onLost(network: Network) {
            super.onLost(network)
            netWorkConnect = false
            listenerList.forEach {
                it.invoke(isNetWorkConnect, isWifi)
            }
        }

        override fun onLinkPropertiesChanged(network: Network, linkProperties: LinkProperties) {
            super.onLinkPropertiesChanged(network, linkProperties)
        }

        override fun onUnavailable() {
            super.onUnavailable()
        }

        override fun onLosing(network: Network, maxMsToLive: Int) {
            super.onLosing(network, maxMsToLive)
        }

        override fun onAvailable(network: Network) {
            super.onAvailable(network)//网络可用
            netWorkConnect = true
            notifyListener()
        }
    }

    /**
     * 通知网络发生变化
     */
    private fun notifyListener() {
        listenerList.forEach {
            it.invoke(isNetWorkConnect, isWifi)
        }
    }

    init {
        netServer.requestNetwork(NetworkRequest.Builder().build(), callBack)
    }

    private val listenerList = mutableListOf<Function2<Boolean, Boolean?, Unit>>()
    /**
     * 监听网络
     */
    fun addNetChangeListener(listener: (isConnect: (Boolean), isWifi: (Boolean?)) -> Unit) {
        if (!listenerList.contains(listener)) {
            listenerList.add(listener)
        }
        listener.invoke(isNetWorkConnect, isWifi)
    }

    /**
     * 移除网络监听
     */
    fun removeNetChangeListener(listener: (isConnect: (Boolean), isWifi: (Boolean?)) -> Unit) {
        if (listenerList.contains(listener)) {
            listenerList.add(listener)
        }
    }
}